package org.itcast.annotationandresttemplate.springCacheApplication;

import org.itcast.annotationandresttemplate.swaggerTest.entity.SwaggerDTO;
import org.itcast.annotationandresttemplate.swaggerTest.mapper.SwaggerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

/**
 * 常用注解：
 * @EnableCaching:   开启缓存注解功能，通常加在启动类上
 * @Cacheable: 在方法执行前查询缓存中是否有数据，如果有数据，则直接返回缓存数据，如果没有缓存数据，调用方法并将方法返回值放到缓存中。
 * @CachePut: 将方法的返回值放到缓存中
 * @CacheEvict: 将一条或多条数据从缓存中删除
 */
@RestController
@RequestMapping("/springcache")
public class SpringCacheController {
    @Autowired
    private SwaggerMapper swaggerMapper;

    @CachePut(cacheNames = "userCache",key="#swaggerDTO.swaggerId") // 使用springcache缓存数据，key的生成：userCache::2
//    @CachePut(cacheNames = "userCache",key = "#result.swaggerId")
//    @CachePut(cacheNames = "userCache",key = "#p0.swaggerId")
//    @CachePut(cacheNames = "userCache",key = "#a0.swaggerId")
//    @CachePut(cacheNames = "userCache",key = "#root.args[0].swaggerId")
    @PostMapping("/save")
    public SwaggerDTO save(@RequestBody SwaggerDTO swaggerDTO) {
        swaggerMapper.save(swaggerDTO);
        return swaggerDTO;
    }

    @GetMapping("/getById")
    @Cacheable(cacheNames = "userCache",key="#swaggerId")  // key的生成：userCache::2
    public SwaggerDTO getById(int swaggerId) {
        return swaggerMapper.getById(swaggerId);
    }

    @DeleteMapping
//    @CacheEvict(cacheNames = "userCache",key="#swaggerId")  // key的生成：userCache::2
    @CacheEvict(cacheNames = "userCache",allEntries = true)  // 删除所有缓存
    public void deleteById(int swaggerId) {
        swaggerMapper.deleteById(swaggerId);
    }
}
